#include "puzzlewindow.h"
#include <QMessageBox>
#include <QRandomGenerator>
#include <QSoundEffect>
#include <QWidget>
#include <QCloseEvent>
#include <QShowEvent>
#include<gamecontrolwindow.h>


PuzzleWindow::PuzzleWindow(int difficulty, WelcomeWindow *welcomeWindow,RecordsManager *recordsManager, QWidget *parent)
    : QWidget(parent), solved(false),m_recordsManager(recordsManager),welcomeWindow(welcomeWindow) ,
    m_difficulty(difficulty), emptyRow(difficulty-1),emptyCol(difficulty-1)
{

    m_bestTimeLabel = new QLabel(this);
    m_bestTimeLabel->setStyleSheet("font-size: 16px; color: #4CAF50;");
    updateBestTimeDisplay();


    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(m_bestTimeLabel);


    gridLayout = new QGridLayout();
    gridLayout->setSpacing(2);
    mainLayout->addLayout(gridLayout);


    int windowWidth = m_difficulty * 100 + 50;  // 每个按钮100px + 边距
    int windowHeight = m_difficulty * 100 + 150; // 包含标签和边距
    setMinimumSize(windowWidth, windowHeight);





    int baseSize = m_difficulty * 100; // 每个按钮100x100像素
    setMinimumSize(baseSize + 50, baseSize + 100); // 留出空间给标签和边距


    // 创建控制窗口
    controlWindow = new GameControlWindow(); // 不要设置父对象
    controlWindow->setWindowFlags(Qt::WindowStaysOnTopHint | Qt::Tool);


    // 连接控制窗口信号
    connect(controlWindow, &GameControlWindow::pauseStateChanged,
            this, [this](bool paused){
                setInteractionEnabled(!paused);
            });


    connect(controlWindow, &GameControlWindow::returnToMain, this, [this](){
        this->close(); // 关闭拼图窗口


    });


    connect(this, &PuzzleWindow::returnToWelcome, [this]() {
        this->welcomeWindow->show(); // 通过成员变量访问
    });

    // 初始化后启动计时
    controlWindow->startTimer();


    // 动态创建按钮数组
    buttons.resize(m_difficulty * m_difficulty);
    originalImage.load(":/res/picture1.png");


    // 分割图片
    int partWidth = originalImage.width() / m_difficulty;
    int partHeight = originalImage.height() / m_difficulty;
    for (int row = 0; row < m_difficulty; ++row) {
        for (int col = 0; col < m_difficulty; ++col) {
            QRect rect(col * partWidth, row * partHeight, partWidth, partHeight);

            imageParts.append(originalImage.copy(rect));
        }
    }



    // 初始化音效
    soundEffect.setSource(QUrl("qrc:/res/move.wav"));

    // 初始化按钮
    int index = 0;
    for (int row = 0; row < m_difficulty; ++row) {
        for (int col = 0; col < m_difficulty; ++col) {
            QPushButton *btn = new QPushButton();
            btn->setFixedSize(100, 100);

            if (row == m_difficulty-1 && col == m_difficulty-1) {
                btn->setIcon(QIcon());
            } else {
                btn->setIcon(QIcon(imageParts[index++]));
            }
            btn->setIconSize(QSize(100, 100));
            gridLayout->addWidget(btn, row, col);
            buttons[row * m_difficulty + col] = btn;

            connect(btn, &QPushButton::clicked, this, &PuzzleWindow::handleButtonClick);
            connect(btn, &QPushButton::clicked, this, [=](){
                soundEffect.play();
            });
        }
    }
    shuffle(); // 打乱拼图

}

void PuzzleWindow::setDifficulty(int newDifficulty)
{
    // 更新难度
    m_difficulty = newDifficulty;

    // 清空按钮和图片分片
    qDeleteAll(buttons);
    buttons.clear();
    imageParts.clear();

    // 清空布局中的所有项
    QLayoutItem *child;
    while ((child = gridLayout->takeAt(0)) != nullptr) {
        delete child->widget(); // 删除布局中的小部件
        delete child;           // 删除布局项
    }

    // 重新加载图片并分割
    originalImage.load(":/res/picture1.png");
    int partWidth = originalImage.width() / m_difficulty;
    int partHeight = originalImage.height() / m_difficulty;
    for (int row = 0; row < m_difficulty; ++row) {
        for (int col = 0; col < m_difficulty; ++col) {
            QRect rect(col * partWidth, row * partHeight, partWidth, partHeight);
            imageParts.append(originalImage.copy(rect));
        }
    }

    // 重新创建按钮
    buttons.resize(m_difficulty * m_difficulty);
    int index = 0;
    for (int row = 0; row < m_difficulty; ++row) {
        for (int col = 0; col < m_difficulty; ++col) {
            QPushButton *btn = new QPushButton();
            btn->setFixedSize(100, 100);

            if (row == m_difficulty-1 && col == m_difficulty-1) {
                btn->setIcon(QIcon());
            }   else {
                btn->setIcon(QIcon(imageParts[index++]));
            }
            btn->setIconSize(QSize(100, 100));
            gridLayout->addWidget(btn, row, col);
            buttons[row * m_difficulty + col] = btn;

            connect(btn, &QPushButton::clicked, this, &PuzzleWindow::handleButtonClick);
            connect(btn, &QPushButton::clicked, this, [=](){
                soundEffect.play();
            });
        }
    }
    // 重置空位位置
    emptyRow = m_difficulty - 1;
    emptyCol = m_difficulty - 1;

    shuffle(); // 打乱拼图

    this->adjustSize(); // 强制调整窗口尺寸
    this->update();      // 重绘界面
}






void PuzzleWindow::handleButtonClick()
{
    QPushButton* clickedButton = qobject_cast<QPushButton*>(sender());
    // 初始化音效，用的时候再拿，succeedSound是在头文件中声明的
    succeedSound.setSource(QUrl("qrc:/res/SucceedSound.wav"));

    // 找到点击按钮的位置
    for (int row = 0; row < m_difficulty; ++row) {
        for (int col = 0; col < m_difficulty; ++col) {
            if (buttons[row * m_difficulty + col] == clickedButton) {
                // 检查是否与空位相邻
                if ((qAbs(row - emptyRow) == 1 && col == emptyCol) ||
                    (qAbs(col - emptyCol) == 1 && row == emptyRow)) {

                    swapButtons(row, col, emptyRow, emptyCol);
                    emptyRow = row;
                    emptyCol = col;

                    if (checkPuzzleSolved()) {
                        controlWindow->stopTimer(); // 关键：停止计时器
                        succeedSound.play();

                    }
                }
                return;
            }
        }
    }
}

void PuzzleWindow::swapButtons(int row1, int col1, int row2, int col2)
{
    QString temp = buttons[row1 * m_difficulty + col1]->text();
    buttons[row1 * m_difficulty + col1]->setText(buttons[row2 * m_difficulty + col2]->text());
    buttons[row2 * m_difficulty + col2]->setText(temp);

    // 交换图标
    QIcon tempIcon = buttons[row1 * m_difficulty + col1]->icon();
    buttons[row1 * m_difficulty + col1]->setIcon(buttons[row2 * m_difficulty + col2]->icon());
    buttons[row2 * m_difficulty + col2]->setIcon(tempIcon);
}

void PuzzleWindow::shuffle()
{
    // 进行50次随机有效移动
    for (int i = 0; i < 50; ++i) {
        QVector<QPair<int, int>> possibleMoves;

        // 寻找所有可能的移动方向
        if (emptyRow > 0) possibleMoves.append(qMakePair(emptyRow - 1, emptyCol));
        if (emptyRow <  m_difficulty - 1) possibleMoves.append(qMakePair(emptyRow + 1, emptyCol));
        if (emptyCol > 0) possibleMoves.append(qMakePair(emptyRow, emptyCol - 1));
        if (emptyCol < m_difficulty - 1) possibleMoves.append(qMakePair(emptyRow, emptyCol + 1));

        // 随机选择一个有效移动
        if (!possibleMoves.isEmpty()) {
            int index = QRandomGenerator::global()->bounded(possibleMoves.size());
            QPair<int, int> move = possibleMoves[index];
            swapButtons(move.first, move.second, emptyRow, emptyCol);
            emptyRow = move.first;
            emptyCol = move.second;
        }
    }
}

bool PuzzleWindow::checkPuzzleSolved()
{
    bool isSolved = true;

    int index = 0;
    for (int row = 0; row < m_difficulty; ++row) {
        for (int col = 0; col < m_difficulty; ++col) {
            if (row == m_difficulty-1 && col == m_difficulty-1) { // 空位检查
                if (!buttons[row * m_difficulty + col]->icon().isNull()) {
                    return false; // 空位不为空，拼图未完成
                }
            } else {
                QImage currentImage = buttons[row * m_difficulty + col]->icon().pixmap(100, 100).toImage();
                QImage originalImage = imageParts[index].toImage();

                // 确保图片大小一致
                if (currentImage.size() != originalImage.size()) {
                    return false;
                }

                // 比较图片内容
                if (currentImage != originalImage) {
                    isSolved = false; // 发现不匹配则未完成
                    return false; // 图片块不匹配，拼图未完成
                }
            }
            index++;
        }
    }
    if (isSolved) {
        solved = true; // 更新成员变量
        controlWindow->stopTimer(); // 停止计时器
        succeedSound.play(); // 播放音效
        QMessageBox::information(this, "成功", "恭喜完成！\n本次时间: " + formatTime(controlWindow->elapsedSeconds));
        m_recordsManager->updateRecord(m_difficulty, controlWindow->elapsedSeconds); // 更新记录
        updateBestTimeDisplay();
    }
    return isSolved; // 直接返回检查结果

}

void PuzzleWindow::closeEvent(QCloseEvent *event)
{
    emit destroyed();
    if(controlWindow) controlWindow->close();
    QWidget::closeEvent(event);

     emit returnToWelcome();
}

void PuzzleWindow::showEvent(QShowEvent *event)
{
    // 控制窗口位置调整逻辑
    if(controlWindow) {
        QPoint newPos = this->pos();
        newPos.setX(newPos.x() + this->width() + 20);
        controlWindow->move(newPos);
        controlWindow->show();
    }
    QWidget::showEvent(event);
}

void PuzzleWindow::setInteractionEnabled(bool enabled)
{
    // 遍历所有按钮设置启用状态
    foreach(QPushButton *btn, buttons) {
        btn->setEnabled(enabled);
    }
}


void PuzzleWindow::updateBestTimeDisplay()
{
    QString bestTime = m_recordsManager->getBestTime(m_difficulty);
    m_bestTimeLabel->setText(tr("最佳记录: ") + bestTime);
}

QString PuzzleWindow::formatTime(int seconds) const
{
    return QString("%1:%2")
    .arg(seconds / 60, 2, 10, QLatin1Char('0'))
        .arg(seconds % 60, 2, 10, QLatin1Char('0'));
}
